#include <db.h>
#include <string.h>

#define DEFAULT_DB_ENV_PATH "/usr/local/bdb/"
#define CACHESIZE (2 * 1024 * 1024)

enum db_op {
    NONE = 0,
    GET,
    PUT,
    LIST,
    DEL
};

int
main(int argc, char **argv)
{
    FILE *errfile = stderr;
    int ret;
    u_int32_t open_flags;
    u_int32_t op = NONE;
    DB_ENV *db_envp;
    DB *dbp;
    char *db_env_path = DEFAULT_DB_ENV_PATH;
    char *db_path = "pair.db";
    char *prog_name = argv[0];
    char *url;
    u_int32_t cache_time;

    if (argc != 2) {
        fprintf(errfile, "Usage: %s <bdb_env_path> \n", argv[0]);
        return -1;
    }

    db_env_path = argv[1];

   /* create db enviroment handler */
    ret = db_env_create(&db_envp, 0);
    if (ret) {
        fprintf(errfile, "Create database enviroment handler failed. %s",
                db_strerror(ret));
        return ret;
    }

    (void)db_envp->set_cachesize(db_envp, 0, CACHESIZE, 0);
    (void)db_envp->set_flags(db_envp, DB_TXN_NOSYNC, 1);
/*
    ret = db_envp->repmgr_set_local_site(db_envp, "127.0.0.1", 4000, 0);
    if (ret) {
        fprintf(errfile, "Set local address failed. %s",
                db_strerror(ret));
        return ret;
    }
*/
/*
    ret = db_envp->repmgr_add_remote_site(db_envp, "127.0.0.1", 4001, NULL, 0);
    if (ret) {
        fprintf(errfile, "Add remote address failed. %s",
                db_strerror(ret));
        return ret;
    }

    ret = db_envp->rep_set_nsites(db_envp, 5);
    if (ret) {
        fprintf(errfile, "Set sites number failed. %s",
                db_strerror(ret));
        return ret;
    }
*/
    /* open the enviroment */
    open_flags = DB_CREATE |    /* Create the environment if it does
                                 * not already exist. */
        DB_INIT_TXN  | /* Initialize transactions */
        DB_INIT_LOCK | /* Initialize locking. */
        DB_INIT_LOG  | /* Initialize logging */
        DB_INIT_MPOOL| /* Initialize the in-memory cache. */
        DB_INIT_REP  |
        DB_THREAD    |
        DB_RECOVER;
    ret = db_envp->open(db_envp, (const char *)db_env_path, open_flags, 0);
    if (ret) {
        fprintf(errfile, "Open database enviroment handler failed for path '%s'. %s",
                      db_env_path, db_strerror(ret));
        return ret;
    }

/*
    ret = db_envp->repmgr_start(db_envp, 3, DB_REP_MASTER);
    if (ret) {
        fprintf(errfile, "Start replication manager failed. %s",
                db_strerror(ret));
        return ret;
    }
*/

    for(;;) {
        sleep(1);
    }

    if (db_envp != NULL) {
        ret = db_envp->close(db_envp, 0);
        if (ret) {
            fprintf(errfile,
                    "Database enviroment '%s' close failed.", db_env_path);
        }
    }
}
